package com.yex.utils;

import com.alibaba.fastjson.JSON;
import com.yex.common.exception.RRException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.net.URLEncoder;
import java.util.Map;


public class ApiSms {

    public static boolean sendSms(String mobile, String templateId, String content) {
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send");
            postMethod.getParams().setContentCharset("UTF-8");
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

            String accesskey = "E4eFqBOKhVQgTNkt";
            String accessSecret = "bUMVyE7N3gqYy6pR5ATr3XFzhqljrlqo";

            NameValuePair[] data = {
                    new NameValuePair("accesskey", accesskey),
                    new NameValuePair("secret", accessSecret),
                    new NameValuePair("sign", "【ETCC】"),
                    new NameValuePair("templateId", templateId),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("content", URLEncoder.encode(content, "utf-8"))
            };

            postMethod.setRequestBody(data);
            postMethod.setRequestHeader("Connection", "close");
            int statusCode = httpClient.executeMethod(postMethod);
            System.out.println("statusCode: " + statusCode + ", body: "
                    + postMethod.getResponseBodyAsString());
            Map map = JSON.parseObject(postMethod.getResponseBodyAsString(), Map.class);
            String code = (String) map.get("code");
            if (!"0".equalsIgnoreCase(code)) {
                throw new RRException(map.get("msg").toString());
            }
            return statusCode == 200 && "0".equals(code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(e.getMessage());
        }
    }


}